package com.example.oasystem.controller.attend;

import com.example.oasystem.dao.status.AoaStatusListDao;
import com.example.oasystem.dao.type.AoaTypeListDao;
import com.example.oasystem.entity.attend.AoaAttendsList;
import com.example.oasystem.entity.dept.AoaDept;
import com.example.oasystem.entity.page.Page;
import com.example.oasystem.entity.status.AoaStatusList;
import com.example.oasystem.entity.type.AoaTypeList;
import com.example.oasystem.entity.user.AoaUser;
import com.example.oasystem.service.AoaStatusListService;
import com.example.oasystem.service.AoaTypeListService;
import com.example.oasystem.service.impl.AoaAttendsListServiceImpl;


import com.example.oasystem.utils.IpUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
public class AttendceController {
    @Autowired
    AoaAttendsListServiceImpl aoaAttendsListService;
    @Autowired
    AoaTypeListDao aoaTypeListDao;
    @Autowired
    AoaTypeListService aoaTypeListService;
    @Autowired
    AoaStatusListService aoaStatusListService;
    @Autowired
    AoaStatusListDao aoaStatusListDao;
    @RequestMapping("/attendceatt")
    public String attendceatt(Model model, HttpServletRequest request,
                              @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                              @RequestParam(value = "baseKey", defaultValue = "") String baseKey) {
        AoaUser sessionUser=(AoaUser) request.getSession().getAttribute("user");

        System.out.println("修改后跳转");
        System.out.println("pageNum="+pageNum+"baseKey="+baseKey);
        if (baseKey.equals(","))
        {
            baseKey="";
        }
        PageInfo<AoaAttendsList> attendsList=aoaAttendsListService.selectAllByNameAndDeptAndLimitAndName(pageNum,pageSize,sessionUser.getUserId().toString(),baseKey);
        List<AoaTypeList> typeList =aoaTypeListDao.selectAll();
        List<AoaStatusList> statusList=aoaStatusListDao.selectAll();
        Page page=new Page(attendsList.getSize(), Math.toIntExact(attendsList.getTotal()),attendsList.getPages(),attendsList.getPageNum(),attendsList.isIsFirstPage(),attendsList.isIsLastPage());
        System.out.println("初始"+page);
        model.addAttribute("statuslist",statusList);
        model.addAttribute("page",page);
        model.addAttribute("typelist",typeList);
        model.addAttribute("baseKey",baseKey);
        model.addAttribute("alist",attendsList.getList());
        model.addAttribute("url","attendcetable");
        return "attendce/attendceview";
    }
    @RequestMapping("/attendcetable")
    public String attendcetable(Model model, HttpServletRequest request,
                                @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,
                                @RequestParam(value = "type", required = false)Integer type,
                                @RequestParam(value = "time", required = false)Integer time,
                                @RequestParam(value = "status", required = false)Integer status,
                                @RequestParam(value = "icon", required = false,defaultValue = "")String icon,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                @RequestParam(value = "baseKey", defaultValue = "") String baseKey) {

        AoaUser sessionUser=(AoaUser) request.getSession().getAttribute("user");
        System.out.println(sessionUser.getUserId()+"这是userid");
       /* PageInfo<AoaAttendsList> attendsList=aoaAttendsListService.selectAllByNameAndDeptAndLimitAndName(pageNum,pageSize,sessionUser.getDeptId().toString(),baseKey);*/
        PageInfo<AoaAttendsList> attendsList=aoaAttendsListService.selectAllByNameAndDeptAndLimitAndNameAndOrder(pageNum,pageSize,sessionUser.getUserId().toString(),baseKey,type,time,status);
        List<AoaTypeList> typeList =aoaTypeListDao.selectAll();
        List<AoaStatusList> statusList=aoaStatusListDao.selectAll();
        Page page=new Page(attendsList.getSize(), Math.toIntExact(attendsList.getTotal()),attendsList.getPages(),attendsList.getPageNum(),attendsList.isIsFirstPage(),attendsList.isIsLastPage());
        System.out.println("选择"+page);

        model.addAttribute("statuslist",statusList);
        model.addAttribute("page",page);
        model.addAttribute("baseKey",baseKey);
        model.addAttribute("type",type);
        model.addAttribute("time",time);
        model.addAttribute("status",status);
        model.addAttribute("icon",icon);
        model.addAttribute("typelist",typeList);
        model.addAttribute("alist",attendsList.getList());
        model.addAttribute("url","attendcetable");
        return "attendce/attendcetable";
    }
    @RequestMapping("/attdelete")
    public String attdelete(@RequestParam(value = "aid",defaultValue = "0") int aid,
                            @RequestParam(value = "pageNum", required = false,defaultValue = "1") int pageNum,

                            Model model){

        if (aid != 0){

            int i = aoaAttendsListService.deleteAttends(aid);
            if (i!=0){
                return "forward:/attendceatt?pageNum="+pageNum;
            }else {
                model.addAttribute("errormess","删除失败");
            }
        }else {
            model.addAttribute("errormess","删除失败");
        }
        return "forward:/attendceatt?pageNum="+pageNum;
    }
    @RequestMapping("/attendceeditOnChenlong")
    public String attendceeditOnChenlong(@RequestParam(value = "aid" ,defaultValue = "0") int aid
                                , Model model
                                , HttpSession session,HttpServletRequest request,
                               @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                               @RequestParam(value = "baseKey", defaultValue = "") String baseKey)
    {
        System.out.println(baseKey+"这是搜索条件"+pageNum+"页码好");
        AoaUser sessionUser=(AoaUser) request.getSession().getAttribute("user");
        AoaAttendsList attends = aoaAttendsListService.findOne(aid);
        System.out.println(attends);
        //查找所有的type
        List<AoaTypeList> allType = aoaTypeListDao.selectAll();
        //查找所有的Status
        List<AoaStatusList> statusList=aoaAttendsListService.findAttendsStatus(attends.getTypeId().intValue());


        session.setAttribute("aid",aid);
        model.addAttribute("status",statusList);
        model.addAttribute("type",allType);
        model.addAttribute("baseKey",baseKey);
        model.addAttribute("attends",attends);
        model.addAttribute("pageNum",pageNum);
        return "attendce/attendceedit2";
    }
    @RequestMapping("/attendcesaveOnChenlong")
    public String attendcesaveOnChenlong(@RequestParam(value = "attendsId",defaultValue = "0")int attendsId,
                               @RequestParam(value = "attendsRemark",defaultValue = "")String attendsRemark,
                               @RequestParam(value = "statusId",defaultValue = "0")int statusId,
                               @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                               @RequestParam(value = "pageSize",defaultValue = "8")int pageSize,
                               @RequestParam(value = "baseKey",defaultValue = "")String baseKey,
                               Model model,HttpSession session,HttpServletRequest request){
        System.out.println(attendsId+"备注 "+attendsRemark+"状态 "+statusId+" 页码"+pageNum+"页面大小 "+pageSize+" 搜索"+baseKey+" ");


        if ( attendsId != 0 ){
            int i = aoaAttendsListService.updateAttends(attendsId, attendsRemark, statusId);

            if (i==0){
                model.addAttribute("errormess","修改失败");
            }
        }else {
            model.addAttribute("errormess","修改失败");
        }
        return attendceatt(model,request,pageNum,pageSize,baseKey);
    }
    String sousuo=null;

    @RequestMapping("/clockIn")
    public String singin(HttpServletRequest request, Model model)throws Exception{

        //时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String nowdatehms = sdf.format(date);  //获取当前系统时间
        // 截取当天时间
        SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd");
        // 星期 判断该日期是星期几
        SimpleDateFormat sdf1 = new SimpleDateFormat("EEEE");
        // 截取时分
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
        // 截取时分秒
        SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss");

        // 一年当中的年月日
        String nowdata = sdf4.format(date);
        // 一周当中的星期几
        String weekofday = sdf1.format(date);
        // 时分
        String hourmin = sdf2.format(date);
        // 时分秒
        String hourminsec = sdf3.format(date);
        //转换为毫秒数
        Calendar calendarHourminsec = Calendar.getInstance();
        calendarHourminsec.setTime(new SimpleDateFormat("HH:mm:ss").parse(hourminsec));



        //设置正常上班时间
        String startwork = "09:00:00";
        //转换为毫秒数
        Calendar calendarStartwork = Calendar.getInstance();
        calendarStartwork.setTime(new SimpleDateFormat("HH:mm:ss").parse(startwork));

        //设置正常下班时间
        String endtwork = "17:00:00";
        //转换为毫秒数
        Calendar calendarEndtwork = Calendar.getInstance();
        calendarEndtwork.setTime(new SimpleDateFormat("HH:mm:ss").parse(endtwork));

        //设置旷工时间
        String absenteeismWork="12:00:00";
        //转换为毫秒数
        Calendar calendarAbsenteeismWork = Calendar.getInstance();
        calendarAbsenteeismWork.setTime(new SimpleDateFormat("HH:mm:ss").parse(absenteeismWork));

        //设置最早打卡时间
        String earliestDK = "8:30:00";
        //转换为毫秒数
        Calendar calendarEarliestDK = Calendar.getInstance();
        calendarEarliestDK.setTime(new SimpleDateFormat("HH:mm:ss").parse(earliestDK));

        //设置最晚打卡时间
        String latestDK ="22:00:00";
        //转换为毫秒数
        Calendar calendarLatestDK = Calendar.getInstance();
        calendarLatestDK.setTime(new SimpleDateFormat("HH:mm:ss").parse(latestDK));


        //判断是否在打卡正常时间
        if (calendarHourminsec.getTimeInMillis()<calendarEarliestDK.getTimeInMillis() || calendarHourminsec.getTimeInMillis()>calendarLatestDK.getTimeInMillis()){
            String error = "1";

            model.addAttribute("error",error);

            return "forward:/test2";
        }

        Long typeId;//8.上班 9.下班

        Long statusId;//10.正常 11.迟到 12.早退 13.旷工
        //获取用户id
        AoaUser user = (AoaUser)request.getSession().getAttribute("user");
        System.out.println("user = " + user);
        Long attanendsUserId = user.getUserId();

        //获取用户ip
        String attendsIp = IpUtil.getIpAddr(request);

        //用户当前的打卡状态
        List<AoaAttendsList> aoaAttendsLists = aoaAttendsListService.AoaAttendsList(attanendsUserId,nowdata);
        //当天没有打卡
        if (aoaAttendsLists.size()==0){

            typeId =8l;//上班


            //正常上班
            if (calendarHourminsec.getTimeInMillis()>calendarEarliestDK.getTimeInMillis()&&calendarHourminsec.getTimeInMillis()<calendarStartwork.getTimeInMillis()){
                statusId = 10l;//正常
                int insertSelective = aoaAttendsListService.insertSelective(new AoaAttendsList(null, attendsIp, "正常上班", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
            //迟到上班
            else if (calendarHourminsec.getTimeInMillis()>=calendarStartwork.getTimeInMillis()&&calendarHourminsec.getTimeInMillis()<calendarLatestDK.getTimeInMillis()){
                statusId = 11l;//迟到
                int insertSelective = aoaAttendsListService.insertSelective(new AoaAttendsList(null, attendsIp, "迟到", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
            //旷工
//            if (calendarHourminsec.getTimeInMillis()>=calendarAbsenteeismWork.getTimeInMillis()&&calendarHourminsec.getTimeInMillis()<calendarLatestDK.getTimeInMillis()){
//                statusId = 13l;//旷工
//                int insertSelective = aoaAttendsListService.insertSelective(new AoaAttendsList(null, attendsIp, "旷工", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
//            }
        }
        //当天打了一次卡
        if (aoaAttendsLists.size()==1){
            AoaAttendsList aoaAttendsList = aoaAttendsLists.get(0);
            model.addAttribute("alist",aoaAttendsList);
            typeId =9l;//下班
            String type = aoaTypeListService.typeName(typeId);
            model.addAttribute("type",type);
            //判断是否在打卡正常时间
//             if (calendarHourminsec.getTimeInMillis()<calendarEarliestDK.getTimeInMillis() && calendarHourminsec.getTimeInMillis()>calendarLatestDK.getTimeInMillis()){
//                 int error = 1;
//                 model.addAttribute("error","error");
//            }
            //正常下班
            if (calendarHourminsec.getTimeInMillis()>=calendarEndtwork.getTimeInMillis()&&calendarHourminsec.getTimeInMillis()<calendarLatestDK.getTimeInMillis()){
                statusId=10l;
                int insertSelective = aoaAttendsListService.insertSelective(new AoaAttendsList(null, attendsIp, "正常下班", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
            //早退
            else if (calendarHourminsec.getTimeInMillis()<calendarEndtwork.getTimeInMillis()){
                statusId=12l;
                int insertSelective = aoaAttendsListService.insertSelective(new AoaAttendsList(null, attendsIp, "早退", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
        }
        //当天打了多次卡
        else if (aoaAttendsLists.size()==2){
            typeId =9l;//下班
            //通过主键搜索得到下班状态并存储
            String type = aoaTypeListService.typeName(typeId);
            model.addAttribute("type",type);

            AoaAttendsList aoaAttendsList = aoaAttendsLists.get(1);
            model.addAttribute("alist",aoaAttendsList);
            //获取主键
            Long attendsId = aoaAttendsList.getAttendsId();
            typeId =9l;//下班
            //判断是否在打卡正常时间
//            if (calendarHourminsec.getTimeInMillis()<calendarEarliestDK.getTimeInMillis() && calendarHourminsec.getTimeInMillis()>calendarLatestDK.getTimeInMillis()){
//                int error = 1;
//                model.addAttribute("error","error");
//            }
            //正常下班
            if (calendarHourminsec.getTimeInMillis()>=calendarEndtwork.getTimeInMillis()&&calendarHourminsec.getTimeInMillis()<calendarLatestDK.getTimeInMillis()){
                statusId=10l;
                int updateByPrimaryKeySelective = aoaAttendsListService.updateByPrimaryKeySelective(new AoaAttendsList(attendsId, attendsIp, "正常下班", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
            //早退
            else if (calendarHourminsec.getTimeInMillis()<calendarEndtwork.getTimeInMillis()){
                statusId=12l;
                int updateByPrimaryKeySelective = aoaAttendsListService.updateByPrimaryKeySelective(new AoaAttendsList(attendsId, attendsIp, "早退", nowdatehms, statusId, typeId, attanendsUserId, hourmin, weekofday, 0.00, null));
            }
        }

        return "forward:/test2";
    }
    @RequestMapping("/attendcelist")
    public String attendList(HttpServletRequest request, @RequestParam(value = "basekey", required = false,defaultValue = "")String baseKey, @RequestParam(value = "page", required = false,defaultValue = "0") int number,Model model){
        AoaUser user = (AoaUser) request.getSession().getAttribute("user");

        Long userId = user.getUserId();
        System.out.println("basekey ppppppppppppppppppp= " + baseKey);
        //查询所有的考勤
        //List<AoaAttendsList> aoaAttendsLists = aoaAttendsListService.aoaAttendsLists(userId);
        if (baseKey.equals(""))
        {
//            baseKey=null;
            sousuo=null;

        }
        else
        {
            sousuo=baseKey;
        }
        List<AoaAttendsList> aoaAttendsLists = aoaAttendsListService.aoaAttendsLists(userId, baseKey);
        int totalElement= aoaAttendsLists.size();
        int size=4;
        int totalPages=totalElement%size==0? totalElement/size:totalElement/size+1;
        boolean first;
        boolean last;
        if (number==0)
        {
            first=true;
        }
        else
        {
            first=false;
        }

        if (number==(totalPages-1))
        {
            last=true;
        }
        else
        {
            last=false;
        }
        Page fenye=new Page(totalElement,size,totalPages,number, first,last);
        List<AoaAttendsList> aoaAttendsListsPageSearch = aoaAttendsListService.aoaAttendsListPageSearch(userId, baseKey, (number) * size, size);
        System.out.println("aoaAttendsListsPageSearch = " + aoaAttendsListsPageSearch);
        //查询上下班类型列表
        List<AoaTypeList> aoaTypeLists = aoaTypeListService.aoaTypeLists();

        //查询上下班状态列表
        List<AoaStatusList> aoaStatusLists = aoaStatusListService.aoaStatusLists();

        model.addAttribute("basekey",baseKey);
        model.addAttribute("alist",aoaAttendsListsPageSearch);
        model.addAttribute("typelist",aoaTypeLists);
        model.addAttribute("statuslist",aoaStatusLists);
        model.addAttribute("page",fenye);
        model.addAttribute("url","attendcelisttable");
        return "/attendce/attendcelist";
    }
    @RequestMapping("/attendcelisttable")
    public String attendcelisttable(int page,Model model,HttpServletRequest request){

        AoaUser user = (AoaUser) request.getSession().getAttribute("user");
        Long userId = user.getUserId();
        //查询所有的考勤
        //List<AoaAttendsList> aoaAttendsLists = aoaAttendsListService.aoaAttendsLists(userId);
        List<AoaAttendsList> aoaAttendsLists = aoaAttendsListService.aoaAttendsLists(userId, sousuo);
        System.out.println("aoaAttendsLists = " + aoaAttendsLists);
        int totalElement= aoaAttendsLists.size();
        int size=4;
        int totalPages=totalElement%size==0? totalElement/size:totalElement/size+1;
        int number=page;
        boolean first;
        boolean last;
        if (number==0)
        {
            first=true;
        }
        else
        {
            first=false;
        }

        if (number==(totalPages-1))
        {
            last=true;
        }
        else
        {
            last=false;
        }
        Page fenye=new Page(totalElement,size,totalPages,number, first,last);
        List<AoaAttendsList> aoaAttendsListsPageSearch = aoaAttendsListService.aoaAttendsListPageSearch(userId, sousuo, (number) * size, size);

        //查询上下班类型列表
        List<AoaTypeList> aoaTypeLists = aoaTypeListService.aoaTypeLists();

        //查询上下班状态列表
        List<AoaStatusList> aoaStatusLists = aoaStatusListService.aoaStatusLists();

        model.addAttribute("basekey",sousuo);
        model.addAttribute("alist",aoaAttendsListsPageSearch);
        model.addAttribute("typelist",aoaTypeLists);
        model.addAttribute("statuslist",aoaStatusLists);
        model.addAttribute("page",fenye);
        model.addAttribute("url","attendcelisttable");;
        return "/attendce/attendcelisttable";
    }
}
